//
//  SettingViewController.m
//  Bus_iPhone
//
//  Created by 修勇 黄 on 12-7-16.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SettingViewController.h"
#import "BusDataManager.h"
#import "DataListViewController.h"
#import "AllCityListViewController.h"
#import "BusSetting.h"
#import "MBProgressHUD.h"
#import "SBJson.h"
#import "NeedUpDataViewController.h"

@interface SettingViewController ()

-(void)showDataListViewController;

-(void)showDownLoadCityViewControllerWithArray:(NSArray *)list;

-(void)showNeedUpDataBusViewControllerWithArray:(NSArray *)list;

-(void)checkLastVersion;

@end

@implementation SettingViewController


@synthesize needUpdataCity=_needUpdataCity;
@synthesize versionDic;
@synthesize settingTableView=_settingTableView;

-(void)dealloc{

    [versionDic release];
    [_needUpdataCity release];
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:@"SettingViewController" bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    _settingTableView.backgroundView=nil;
    _settingTableView.backgroundColor=[UIColor clearColor];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void)viewDidAppear:(BOOL)animated{

    [super viewDidAppear:animated];
    [(UITableView *)[self.view viewWithTag:10] reloadData];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -UITableViewDataSourceAndDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    switch (section) {
        case 0:
            return 3;
            break;
        case 1:
            return 3;
        default:
            return 0;
            break;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *cellString=@"setting";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellString];
    if (!cell) {
        cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellString] autorelease];
    }
    
    cell.selectionStyle=UITableViewCellSelectionStyleBlue;
    
    BusDataManager *bus=[BusDataManager currentBusDataManager];
    
    NSString *textString=nil;
    NSString *detailString=nil;
    
    switch (indexPath.section) {
        case 0:
        {
        
            switch (indexPath.row) {
                case 0:
                    textString=@"当前城市:";
                    NSString *busCity=[bus cityName];
                    if (busCity) {
                        detailString=[NSString stringWithFormat:@"%@ (%@)",[bus cityName],[bus date]];
                    }else {
                        detailString=@"";
                    }
                    
                    break;
                case 1:
                    textString=@"其他城市";
                    break;
                case 2:
                    textString=@"数据更新";
                    break;
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            switch (indexPath.row) {
                case 0:
                {
                    NSDictionary *infoDic=[[NSBundle mainBundle]infoDictionary];
                    textString=[NSString stringWithFormat:@"%@",[infoDic objectForKey:@"CFBundleDisplayName"]];
                    NSString *version=[infoDic objectForKey:@"CFBundleVersion"];
                    detailString=[NSString stringWithFormat:@"v %@",version];
                    break;
                }
                case 1:
                    textString=@"检查版本更新";
                    break;
                case 2:
                    detailString=@"http://www.chabus.cn             ";
                    break;
                default:
                    break;
            }
        }
            break;
        default:
            break;
    }
    cell.textLabel.text=textString;
    cell.detailTextLabel.text=detailString;
    
    if (indexPath.section==0) {
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }else
        cell.accessoryType=UITableViewCellAccessoryNone;
    
    
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                    [self showDataListViewController];
                    break;
                case 1:
                    [self showDownLoadCityViewControllerWithArray:nil];
                    break;
                case 2:
                    [self checkDataUpdate];
                    break;
                default:
                    break;
            }
        }
            break;
        case 1:
        {
            switch (indexPath.row) {
                case 1:
                    [self checkLastVersion];
                    break;
                case 2:
                    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"http://www.chabus.cn"]];
                    break;
                default:
                    break;
            }
        }
            break;
        default:
            break;
    }
}


-(void)showDataListViewController{

    DataListViewController *dataList=[[DataListViewController alloc]initWithStyle:UITableViewStylePlain];
    dataList.title=@"已下载的数据";
    [self.navigationController pushViewController:dataList animated:YES];
    [dataList release];
}

-(void)showDownLoadCityViewControllerWithArray:(NSArray *)list{

    AllCityListViewController *down=[[AllCityListViewController alloc]initWithNibName:@"AllCityListViewController" bundle:nil];
    down.title=@"选择城市";
    
    [self.navigationController pushViewController:down animated:YES];
    [down release];
}


-(void)showNeedUpDataBusViewControllerWithArray:(NSArray *)list{

    NeedUpDataViewController *need=[[NeedUpDataViewController alloc]initWithStyle:UITableViewStylePlain];
    need.title=@"可以更新的城市";
    need.list=list;
    [self.navigationController pushViewController:need animated:YES];
    [need release];
}

-(void)checkDataUpdate{

    NSArray *fileList=[[BusSetting defaultSetting]getDownLoadDataList];
    if (fileList.count==0) {
        return;
    }
    
    NSMutableArray *tempArray=[NSMutableArray new];
    
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDir = [documentPaths objectAtIndex:0];
    
    for (NSString *fileName in fileList) {
        NSString *filePath=[documentDir stringByAppendingPathComponent:fileName];
        [tempArray addObject:filePath];
    }
    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:@"checkDataIsUpload",@"action",[[BusDataManager currentBusDataManager]queryAllBusDataUpdateByPathList:tempArray],@"citys", nil];
    [tempArray release];
    
    checkCityRequest=[[[BusSetting defaultSetting]webService]postRequestWithDic:dic];
    if (checkCityRequest) {
        checkCityRequest.delegate=self;
        [checkCityRequest startAsynchronous];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }else {
        [self showAlertWithTitle:@"提示" msg:@"连接建立失败!请检查一下网络设置"];
    }
    
}

-(void)checkLastVersion{

    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:@"getLatestVersion",@"action",@"iOS",@"system",@"iPhone",@"device",@"1.0",@"version", nil];
    checkVersionRequest=[[[BusSetting defaultSetting]webService]postRequestWithDic:dic];
    if (checkVersionRequest) {
        checkVersionRequest.delegate=self;
        [checkVersionRequest startAsynchronous];
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }else {
        [self showAlertWithTitle:@"提示" msg:@"连接建立失败!请检查一下网络设置"];
    }
}

#pragma mark -ASIHTTPRequest

-(void)requestFailed:(ASIHTTPRequest *)request{

    NSLog(@"request %@",request.responseString);
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    if ([request isEqual:checkCityRequest]) {
        [self showAlertWithTitle:@"失败" msg:@"检查数据更新失败!"];
        checkCityRequest=nil;
    }else {
        checkVersionRequest=nil;
        [self showAlertWithTitle:@"失败" msg:@"检查版本失败!"];
    }
    
}

-(void)requestFinished:(ASIHTTPRequest *)request{

    NSLog(@"reqyest %@",request.responseString);
    NSLog(@"request url %@",request.url);
    //NSLog(@"request url %@",request.url);
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    NSDictionary *dataDic=nil;
    if ([self isIos5Later]) {
        dataDic=[NSJSONSerialization JSONObjectWithData:[request.responseString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
    }else {
        dataDic=[request.responseString JSONValue];
    }

    if (dataDic==nil) {
        [self showAlertWithTitle:@"提示" msg:@"数据请求失败"];
        
    }else {
        if ([request isEqual:checkCityRequest]) {
            if ([[dataDic objectForKey:@"result"] isEqualToString:@"0"]) {
                [self showAlertWithTitle:@"提示" msg:[dataDic objectForKey:@"text"]];
            }else {
                self.needUpdataCity=[dataDic objectForKey:@"data"];
                NSMutableString *tempCitysName=[[NSMutableString alloc]initWithString:@" "];
                for (NSDictionary *tempCityDic in _needUpdataCity) {
                    [tempCitysName appendFormat:@"%@ ",[tempCityDic objectForKey:@"CityName"]]; 
                }
                NSString *msg=[NSString stringWithFormat:@"%@有新数据是否要更新?",tempCitysName];
                [tempCitysName release];
                UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
                [alert show];
                [alert release];
                isCityUpData=YES;
            }
        }else {
            if ([[dataDic objectForKey:@"result"] isEqualToString:@"0"]) {
                [self showAlertWithTitle:@"提示" msg:[dataDic objectForKey:@"text"]];
            }else {
                self.versionDic=dataDic;
                NSString *msg=[NSString stringWithFormat:@"%@ 版本已经发布是否去更新?",[dataDic objectForKey:@"version"]];
                UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
                [alert show];
                [alert release];
                isCityUpData=NO;
            }
        }
    }
    
    checkCityRequest=nil;
    
}


#pragma mark -UIAlertViewDelegate

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (buttonIndex==1) {
        if (isCityUpData) {
            self.tabBarController.selectedViewController=self.navigationController;
            [self showNeedUpDataBusViewControllerWithArray:_needUpdataCity];
        }else {
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[versionDic objectForKey:@"downURL"]]];
        }
    }
}
@end
